<?php

namespace App\Http\Controllers\Admin;

use App\Models\Manage;
use App\Models\ScoreInfo;
use App\Models\ScoreLog;
use App\Models\ScoreRule;
use App\Models\UserLibraryInfo;
use App\Validate\ScoreInfoValidate;
use Illuminate\Support\Facades\DB;


/**
 * 积分设置
 */
class ScoreInfoController extends CommonController
{
    protected $model = null;
    protected $validate = null;
    public function __construct()
    {
        parent::__construct();

        $this->model = new ScoreInfo();
        $this->validate = new ScoreInfoValidate();
    }

    /**
     * 积分规则列表
     * @param page int 当前页
     * @param limit int 分页大小
     */
    public function lists()
    {
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;

        $res = $this->model
            ->select('id', 'type', 'type_name', 'score', 'number', 'node', 'intro', 'is_open', 'create_time')
            ->where('is_del', 1)
            ->paginate($limit)
            ->toArray();

        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }

        $res = $this->disPageData($res);
        $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);

        return $this->returnApi(200, "查询成功", true, $res);
    }


    /**
     * 设置规则
     * @param id int 积分规则id
     * @param score int 消耗或获得的积分
     * @param number int 一天最多几次  
     * @param intro string 规则简介
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }


        $score_info = $this->model->where('is_del', 1)->find($this->request->id);

        if (!$score_info) {
            return $this->returnApi(201, '参数传递错误');
        }

        if ($score_info->node == 1 && $this->request->score < 0) {
            return $this->returnApi(201, '积分不允许小于0');
        }
        if ($score_info->node == 2 && $this->request->score > 0) {
            return $this->returnApi(201, '积分不允许大于0');
        }


        /*if((!$this->request->score && $this->request->score !== 0 ) && (!$this->request->number && $this->request->number !== 0)){
            return $this->returnApi(201,'参数传递错误');
        }*/

        $score = $this->request->score;
        $state = $score >= 0 ? '增加' : '减少';
        $state =  $this->request->id == 14 ? '将额外' . $state : $state; //id 14 特殊处理
        $intro = $score_info->type_name . $state . ' ' . abs($score) . ' ' . '积分';
        $number = in_array($this->request->id, [1, 13, 14, 19]) ? 1 : $this->request->number; //前1条，只能设置一次
        if (!empty($number) && !in_array($this->request->id, [1, 13, 14, 19])) {
            $intro .= '（每日限制' . $number . '次）';
        }

        $score_info->score = $score;
        $score_info->number = $number;
        $score_info->intro = $intro;
        $score_info->is_open = empty($score) ? 2 : 1;
        $score_info->change_time = date('Y-m-d H:i:s');
        $res = $score_info->save();

        if (!$res) {
            return $this->returnApi(202, "修改失败");
        }

        return $this->returnApi(200, "修改成功", true);
    }

    /**
     * 积分变动记录
     * @param account_id int 读者证用户id
     * @param page int 页码
     * @param limit int 分页大小
     * @param keywords string 搜索项(姓名，电话，身份证)
     * @param start_time datetime 开始时间(积分变动时间)
     * @param end_time datetime 结束时间(积分变动时间)
     */
    public function scoreLog()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('score_log')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $account_id = $this->request->account_id;

        $scoreLogModel = new ScoreLog();
        $score_log_table = $scoreLogModel->table;

        $userLibInfoModel = new UserLibraryInfo();
        $user_lib_info_table = $userLibInfoModel->table;

        $manageModel = new Manage();
        $manage_table = $manageModel->table;


        $res = $scoreLogModel
            ->from($score_log_table . ' as a')
            ->select('a.account_id', 'a.score', 'a.type', 'type_id', 'intro', 'b.username', 'b.id_card', 'b.tel', 'a.create_time', 'c.username as admin_username')
            ->leftJoin("$user_lib_info_table as b", 'b.id', '=', 'a.account_id')
            ->leftJoin("$manage_table as c", 'a.manage_id', '=', 'c.id')
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('a.type', 'like', "%$keywords%")
                        ->orWhere('a.intro', 'like', "%$keywords%");
                }
            })->where(function ($query) use ($start_time, $end_time) {
                if ($start_time && $end_time) {
                    $query->whereBetween('a.create_time', [$start_time, $end_time]);
                }
            })
            ->where('a.account_id', $account_id)
            ->orderByDesc('a.create_time')
            ->paginate($limit)
            ->toArray();

        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }
        $res = $this->disPageData($res);
        $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 自动调整用户积分
     * @param account_id int 读者证用户id
     * @param score int 调整的积分
     * @param reason text 调整原因
     */
    public function scoreChange()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('score_change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $userLibInfoModel = new UserLibraryInfo();
        $scoreLogModel = new ScoreLog();

        $account_id = $this->request->account_id;
        $score = $this->request->score;
        $reason = $this->request->reason;

        $user_lib = $userLibInfoModel->find($account_id);

        $user_lib->score = $user_lib->score + $score;

        $insert_data = [
            'account_id' => $account_id,
            'score' => $score,
            'intro' => $reason,
            'type_id' => 1000,
            'type' => '管理员手动调整积分',
            'manage_id' => $this->request->manage_id,
        ];

        // 启动事务
        DB::beginTransaction();
        try {
            $user_lib->save();
            $scoreLogModel->add($insert_data);

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "调整成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, "调整失败");
        }
    }




    /**
     * 获取自定义积分规则
     */
    public function customScoreRule()
    {
        $scoreRuleModel = new ScoreRule();
        $res = $scoreRuleModel->select('id', 'intro')->first();

        if ($res) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(202, '获取失败');
    }

    /**
     * 设置自定义积分规则
     * @param $intro 自定义内容 
     */
    public function customScoreRuleChange()
    {
        $scoreRuleModel = new ScoreRule();
        $res = $scoreRuleModel->first();
        if ($res) {
            $res->intro = $this->request->intro;
            $result = $res->save();
        } else {
            $scoreRuleModel->intro = $this->request->intro;
            $result = $scoreRuleModel->save();
        }

        if ($result) {
            return $this->returnApi(200, '获取成功', true);
        }
        return $this->returnApi(202, '获取失败');
    }
}
